package org.nf.web.servlet.param;

import jakarta.servlet.http.HttpServletRequest;
import org.nf.web.servlet.annotation.RequestParam;
import org.nf.web.servlet.ServletApi;

import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;

/**
 * @author wangl
 * @date 2022/6/13
 * 负责解析带有@RequestParam注解的参数
 */
public class RequestParamMethodArgumentResolver extends AbstractMethodArgumentResolver {

    @Override
    public boolean supports(Parameter parameter) {
        return parameter.isAnnotationPresent(RequestParam.class);
    }

    @Override
    public Object resolve(Parameter parameter, ServletApi servletApi) {
        Object value = null;
        HttpServletRequest request = servletApi.request();
        //获取注解value属性名，value的值对应是请求参数的name
        String paramName = parameter.getAnnotation(RequestParam.class).value();
        //获取参数类型
        Class<?> paramType = parameter.getType();
        if(paramType.isArray()) {
            paramType = paramType.getComponentType();
            value = toArray(paramType, request.getParameterValues(paramName));
        } else if(Collection.class.isAssignableFrom(paramType)) {
            //获取集合泛型参数类型
            ParameterizedType parameterizedType = (ParameterizedType) parameter.getParameterizedType();
            Class<?> genericType = (Class<?>) parameterizedType.getActualTypeArguments()[0];
            value = toCollection(paramType, genericType, request.getParameterValues(paramName));
        } else {
            value = toValue(paramType, request.getParameter(paramName));
        }
        return value;
    }
}
